<template>
  <div class="container">
    <div class="search flex-yc flex-xbt">
      <h2>数据库列表</h2>
      <el-button type="primary" @click="onAddDataBase">新增数据库</el-button>
    </div>
    <table-comp index :column="column" :list="dataBaseCateGoryTreeList">
      <template v-slot:handlerSlot="{ row }">
        <!--        <el-button type="success" link>建立分支</el-button>-->
        <el-button
          type="primary"
          link
          @click="onUpdateDataBaseCateGory(row.id, row.parentCategoryId)"
        >
          编辑
        </el-button>
        <el-button type="danger" link @click="onDelDataBaseCateGory(row.id)">
          删除
        </el-button>
      </template>
    </table-comp>
  </div>
  <dia-log title="新建数据库" v-model="visible" @onSubmit="onAddDataBaseSubmit">
    <form-comp
      :form-item="formItem"
      v-model:formData="dataBaseCategoryData"
      :label-width="100"
    >
      <template v-slot:childrenSlot="{ data }">
        <div>
          <el-button type="primary" link @click="onAddDataBaseChildrenCategory">
            添加
          </el-button>
          <div
            class="flex-yc"
            style="margin-bottom: 5px"
            v-for="(item, i) in data"
            :key="item.id"
          >
            <el-input
              size="small"
              v-model="item.databaseCategoryName"
            ></el-input>
            <el-button
              type="primary"
              link
              @click="delDataBaseChildrenCategory(i, item)"
            >
              删除
            </el-button>
          </div>
        </div>
      </template>
    </form-comp>
  </dia-log>
</template>
<script setup lang="ts">
import TableComp from '@/components/table/index.vue'
import DiaLog from '@/components/dialog/index.vue'
import FormComp from '@/components/form/form.vue'
import { onMounted, reactive, ref } from 'vue'
import { tableColumn } from '@/components/table/column'

import {
  respDataBaseCategoryData,
  respDataBaseCategoryTreeData,
} from '@/api/types/database'
import {
  API,
  reqAddOrUpdateDataBaseCategory,
  reqDeleteDataBaseCategory,
  reqGetDataBaseCategory,
} from '@/api/database.ts'
import {
  arrToTree,
  MsgConfirmAsync,
  MsgError,
  MsgSuccess,
} from '@/utils/utils.ts'
import { FormItemType } from '@/components/form/type'

const column = reactive<tableColumn[]>([
  { label: '数据库ID', prop: 'id' },
  { label: '数据库名称', prop: 'databaseCategoryName' },
  { label: '数据库类型', prop: 'parentCategoryName' },
  { label: '发布时间', prop: 'createTime' },
  { label: '操作', prop: '-', type: 'slot', slotName: 'handlerSlot' },
])

onMounted(() => {
  getDataBaseCategory()
})

// 数据库分类
const dataBaseCateGoryTreeList = ref<respDataBaseCategoryTreeData[]>([])
const getDataBaseCategory = async (reqData = {}) => {
  const { data } = await reqGetDataBaseCategory(reqData)
  dataBaseCateGoryTreeList.value = arrToTree(data, null, {
    label: 'databaseCategoryName',
    parentId: 'parentCategoryId',
  })
}

const onDelDataBaseCateGory = async (id: number) => {
  if (await MsgConfirmAsync('你确定删除吗?')) {
    const { data } = await reqDeleteDataBaseCategory(id)
    if (data === 'success') {
      MsgSuccess('删除成功')
      getDataBaseCategory()
    } else MsgError('删除失败')
  }
}

const onUpdateDataBaseCateGory = async (id: number, parentId = null) => {
  const { data } = await reqGetDataBaseCategory({ id })
  const resp: respDataBaseCategoryTreeData[] = arrToTree(data, parentId, {
    label: 'databaseCategoryName',
    parentId: 'parentCategoryId',
  })
  console.log(data, resp, 555)
  const children = await reqGetDataBaseCategory({ parentCategoryId: id })
  dataBaseCategoryData.id = id
  dataBaseCategoryData.databaseCategoryName = resp[0].databaseCategoryName
  dataBaseCategoryData.parentCategoryId = resp[0].parentCategoryId
  dataBaseCategoryData.children = children.data
  visible.value = true
}

const dataBaseCategoryData = reactive<respDataBaseCategoryTreeData>({
  databaseCategoryName: '',
  parentCategoryId: '',
  isNode: 0,
  status: 0,
  children: [],
})
const formItem = ref<FormItemType[]>([
  {
    type: 'input',
    label: '数据库名字',
    prop: 'databaseCategoryName',
    required: true,
  },
  {
    type: 'select',
    label: '选择类型',
    prop: 'parentCategoryId',
    required: true,
    props: { label: 'databaseCategoryName', value: 'id' },
    async: {
      url: API.DATA_BASE_ROOT_CATEGORY_URL,
      method: 'post',
      fetchSearch: true,
      initRequest: true,
    },
  },
  {
    type: 'slot',
    label: '分支',
    prop: 'children',
    slotName: 'childrenSlot',
    required: true,
  },
])
// 弹窗
const visible = ref(false)
const onAddDataBase = () => {
  visible.value = true
}

const dataBaseId = ref(0)
const dataBaseChildCategoryData = ref<respDataBaseCategoryData[]>([])
const onAddDataBaseSubmit = async () => {
  if (!dataBaseCategoryData.databaseCategoryName?.length) {
    return MsgError('请输入名称')
  }
  dataBaseChildCategoryData.value = dataBaseCategoryData.children || []
  delete dataBaseCategoryData.children

  if (dataBaseId.value) dataBaseCategoryData.id = dataBaseId.value
  const { code, data } =
    await reqAddOrUpdateDataBaseCategory(dataBaseCategoryData)
  if (code === 0 && data) {
    let databaseCategoryNameAry: string[] = []
    if (dataBaseChildCategoryData.value.length > 0) {
      dataBaseChildCategoryData.value.forEach(async (item) => {
        item.parentCategoryId = data
        const resp = await reqAddOrUpdateDataBaseCategory(item)
        if (!resp.data) databaseCategoryNameAry.push(item.databaseCategoryName)
      })
      if (databaseCategoryNameAry.length > 0) {
        MsgError(`分支'${databaseCategoryNameAry.join('|')}'提交失败`)
      }
    }

    MsgSuccess('提交成功')
    location.reload()
  } else {
    MsgError('提交失败')
  }
}

const onAddDataBaseChildrenCategory = () => {
  if (!dataBaseCategoryData.children) dataBaseCategoryData.children = []
  dataBaseCategoryData.children?.push({
    databaseCategoryName: '',
    isNode: 0,
    parentCategoryId: 0,
    status: 0,
  })
}

const delDataBaseChildrenCategory = async (
  index: number,
  categoryItem: respDataBaseCategoryData,
) => {
  if (categoryItem.id) {
    const flag = await MsgConfirmAsync('你确定删除吗?')
    if (!flag) return false
    const { data } = await reqDeleteDataBaseCategory(categoryItem.id)
    if (data !== 'success') return false
  }
  dataBaseCategoryData.children?.splice(index, 1)
}
</script>

<style scoped lang="scss">
.container {
  background-color: #fff;
  padding: 10px 0;

  .search {
    padding: 5px 10px;
  }
}
</style>
